package com.zh.service.impl;

import com.zh.config.EmailConfig;
import com.zh.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service("emailService")
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailConfig emailConfig;

    // 发送邮件
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public boolean sendSimpleEmail(String to, String code) {
        // 创建简单的邮件信息
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 谁发的
        simpleMailMessage.setFrom(emailConfig.getFrom());
        // 谁要接受
        simpleMailMessage.setTo(to);
        // 邮件辩题
        simpleMailMessage.setSubject("我是邮件的标题");
        // 邮件内容
        simpleMailMessage.setText("我是邮件的内容");
        try{
            javaMailSender.send(simpleMailMessage);
            return true;
        }catch (MailException e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean sendHtmlEmail(String to, String code) throws MessagingException {
        //创建一个MINE消息
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
        //谁发
        minehelper.setFrom(emailConfig.getFrom());
        //谁要接收
        minehelper.setTo(to);
        //邮件主题
        minehelper.setSubject("我是邮件的标题");
        //邮件内容   true 表示带有附件或html
        minehelper.setText("<p style='color:red'>我是邮件的内容</p>", true);
        try {
            javaMailSender.send(message);
            return true;
        } catch (MailException e) {
            e.printStackTrace();
        }
        return false;
    }
}
